<?php
// 引入依赖类
require_once './lib/StaffDB.php';
require_once './lib/Request.php';
require_once './lib/Response.php';

try {
  $request = new Request();
  $staffDB = new StaffDB();
  $method  = $request->getMethod();

  // -------------------------- 1. 查询员工（GET） --------------------------
  if ($method === 'GET') {
    // 1.1 解析筛选参数
    $filters = [
      // 基础筛选条件（多值用逗号分隔）
       'organizations'  => $request->getGet('organizations') ? explode(',', $request->getGet('organizations')) : [],
      'qualifications' => $request->getGet('qualifications') ? explode(',', $request->getGet('qualifications')) : [],
      'groups'         => $request->getGet('groups') ? explode(',', $request->getGet('groups')) : [],
      'availableSeats' => $request->getGet('availableSeats') ? explode(',', $request->getGet('availableSeats')) : [],
      // 临时角色筛选（JSON格式字符串）
       'temporaryRoles' => $request->getGet('temporaryRoles') ? json_decode($request->getGet('temporaryRoles'), true) : [],
    ];
    $outputType = $request->getGet('type', 'list');            // list/detail
    $all        = $request->getGet('all', 'false') === 'true'; // 是否查询所有

    // 1.2 验证临时角色参数格式
    if (! empty($filters['temporaryRoles']) && ! is_array($filters['temporaryRoles'])) {
      Response::error('临时角色筛选参数格式错误，应为JSON对象');
    }

    // 1.3 执行查询
    if ($all) {
      // 查询所有员工
      $result = $outputType === 'detail'
        ? $staffDB->getAllStaff()
        : $staffDB->getStaffList();
    } else {
      // 按条件筛选
      $result = $staffDB->searchStaff($filters, $outputType === 'detail');
    }

    // 1.4 返回结果
    Response::success([
      'count' => count($result),
      'type'  => $outputType,
      'data'  => $result,
    ], '查询成功');
  }

  // -------------------------- 2. 新建员工（POST） --------------------------
  elseif ($method === 'POST') {
    $staffData = $request->getPost();

    if (! is_array($staffData)) {
      Response::error('请求数据应为数组或对象');
    }

    // 批量/单个创建判断
    $isBatch = isset($staffData[0]) && is_array($staffData[0]);
    $created = [];

    try {
      if ($isBatch) {
        foreach ($staffData as $item) {
          if (empty($item['id']) || empty($item['name'])) {
            throw new Exception("缺少id或name（批量数据中某条记录）");
          }
          $guid      = $staffDB->createStaff($item);
          $created[] = ['guid' => $guid, 'id' => $item['id'], 'name' => $item['name']];
        }
      } else {
        if (empty($staffData['id']) || empty($staffData['name'])) {
          throw new Exception("缺少必要字段：id或name");
        }
        $guid      = $staffDB->createStaff($staffData);
        $created[] = ['guid' => $guid, 'id' => $staffData['id'], 'name' => $staffData['name']];
      }

      Response::created([
        'count' => count($created),
        'data'  => $created,
      ], $isBatch ? '批量创建成功' : '创建成功');
    } catch (Exception $e) {
      Response::error($e->getMessage());
    }
  }

  // -------------------------- 3. 更新员工（PUT） --------------------------
  elseif ($method === 'PUT') {
    $updateData = $request->getPost();

    if (! is_array($updateData)) {
      Response::error('请求数据应为数组或对象');
    }

    // 批量/单个更新判断
    $isBatch = isset($updateData[0]) && is_array($updateData[0]);
    $updated = [];

    try {
      if ($isBatch) {
        foreach ($updateData as $item) {
          if (empty($item['guid'])) {
            throw new Exception("缺少guid（批量数据中某条记录）");
          }
          $staffDB->updateStaff($item);
          $updated[] = ['guid' => $item['guid'], 'message' => '更新成功'];
        }
      } else {
        if (empty($updateData['guid'])) {
          throw new Exception("缺少必要字段：guid");
        }
        $staffDB->updateStaff($updateData);
        $updated[] = ['guid' => $updateData['guid'], 'message' => '更新成功'];
      }

      Response::success([
        'count' => count($updated),
        'data'  => $updated,
      ], $isBatch ? '批量更新成功' : '更新成功');
    } catch (Exception $e) {
      Response::error($e->getMessage());
    }
  }

  // -------------------------- 4. 删除员工（DELETE） --------------------------
  elseif ($method === 'DELETE') {
    $deleteData = $request->getPost();

    if (! is_array($deleteData)) {
      Response::error('请求数据应为数组或对象');
    }

    // 批量/单个删除判断
    $isBatch = isset($deleteData[0]) && is_array($deleteData[0]);
    $deleted = [];

    try {
      if ($isBatch) {
        foreach ($deleteData as $item) {
          if (empty($item['guid'])) {
            throw new Exception("缺少guid（批量数据中某条记录）");
          }
          $success = $staffDB->deleteStaff($item['guid']);
          if ($success) {
            $deleted[] = ['guid' => $item['guid'], 'message' => '删除成功'];
          } else {
            throw new Exception("删除员工失败，GUID: " . $item['guid']);
          }
        }
      } else {
        if (empty($deleteData['guid'])) {
          throw new Exception("缺少必要字段：guid");
        }
        $success = $staffDB->deleteStaff($deleteData['guid']);
        if ($success) {
          $deleted[] = ['guid' => $deleteData['guid'], 'message' => '删除成功'];
        } else {
          throw new Exception("删除员工失败，GUID: " . $deleteData['guid']);
        }
      }

      Response::success([
        'count' => count($deleted),
        'data'  => $deleted,
      ], $isBatch ? '批量删除成功' : '删除成功');
    } catch (Exception $e) {
      Response::error($e->getMessage());
    }
  }

  // -------------------------- 5. 不支持的方法 --------------------------
  else {
    Response::error('不支持的请求方法', null, 405);
  }

} catch (Exception $e) {
  Response::error('操作失败', $e->getMessage());
}